package com.iraeta.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iraeta.entity.*;
import com.iraeta.entity.vo.WeiXinUserInfo;
import com.iraeta.mapper.sys.SysOrgMapper;
import com.iraeta.mapper.sys.SysOrguserMapper;
import com.iraeta.mapper.sys.UserMapper;
import com.iraeta.service.sys.ISysOrgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2023-12-18
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements ISysOrgService {
    private static final Logger logger = LoggerFactory.getLogger(SysOrgServiceImpl.class);

    @Resource
    WeiXinService weiXinService;
    @Resource
    UserMapper userMapper;
    @Resource
    SysOrguserMapper sysOrguserMapper;

    /*获取组织下的所有机构的 树形结构*/
    @Override
    public List<TreeNode> listChildrenOrg(Integer orgId){
        String orgIdStr = String.valueOf(orgId);
        List<SysOrg> sysOrgList = baseMapper.selectAllChildrenOrg(orgId);
        SysOrg rootSysOrg = sysOrgList.stream().filter(x->x.getId().toString().equals(orgIdStr)).findFirst().get();
        TreeNode rootTreeNode = new TreeNode(rootSysOrg.getId().toString(), rootSysOrg.getName());
        listChildrenOrgLoop(rootTreeNode, sysOrgList);
        ArrayList<TreeNode> res = new ArrayList<>();
        res.add(rootTreeNode);
        return res;
    }
    private void listChildrenOrgLoop(TreeNode treeNode, List<SysOrg> sysOrgList){
        String orgIdStr = String.valueOf(treeNode.id);
        List<SysOrg> childOrgList = sysOrgList.stream().filter(x-> x.getPid().toString().equals(orgIdStr)).collect(Collectors.toList());
        for(SysOrg childOrg : childOrgList){
            TreeNode childTreeNode = new TreeNode(childOrg.getId().toString(), childOrg.getName());
            treeNode.addNode(childTreeNode);
            listChildrenOrgLoop(childTreeNode, sysOrgList);
        }
    }

    public List<SysOrg> listOrgOfWeiXin(){
        QueryWrapper<SysOrg> qw = new QueryWrapper<>();
        qw.gt("id", 1);
        return baseMapper.selectList(qw);        //查询同步的企业微信org， 自定义的都是小于等于1的
    }

    @Override
    @Transactional
    public void tongBuOrg(){
        List<SysOrg> sysOrgList = weiXinService.getWeiXinOrg();
        for(SysOrg sysOrg : sysOrgList){        //sysOrg的PID不准确  是企业微信的pid， 要转本系统的pid || SysOrg中默认有id
            SysOrg sysOrgDb = baseMapper.selectById(sysOrg.getId());
            SysOrg sysOrgDbParent = baseMapper.selectById(sysOrg.getPid());
            if(sysOrgDb != null){
                sysOrgDb.setName(sysOrg.getName());
                if(sysOrgDbParent == null){
                    sysOrgDb.setPid(1);
                    sysOrgDb.setMember("1," + sysOrgDb.getId());
                }else{
                    sysOrgDb.setPid(sysOrgDbParent.getId());
                    sysOrgDb.setMember(sysOrgDbParent.getMember() + "," + sysOrgDb.getId());
                }
                baseMapper.updateById(sysOrgDb);
            }else{
                if(sysOrgDbParent == null){
                    sysOrg.setPid(CustomOrg.root);
                    sysOrg.setMember(CustomOrg.root + "," + sysOrg.getId());
                }else{
                    sysOrg.setPid(sysOrgDbParent.getId());
                    sysOrg.setMember(sysOrgDbParent.getMember() + "," + sysOrg.getId());
                }
                baseMapper.insert(sysOrg);
            }
        }
    }
    @Override
    @Transactional
    public void tongBuUser(){
        List<SysOrg> sysOrgList = this.listOrgOfWeiXin();
        for(SysOrg sysOrg : sysOrgList){
            try {
                List<WeiXinUserInfo> weiXinUserInfoList = weiXinService.getOrgWeiXinUserInfo(sysOrg.getId());
                for(WeiXinUserInfo weiXinUserInfo : weiXinUserInfoList){
                    User user = userMapper.selectUserByWxid(weiXinUserInfo.getUserid());
                    if(user == null){
                        user = new User();
                        user.setUsername(weiXinUserInfo.getUserid());
                        user.setPwd(weiXinUserInfo.getUserid());
                        user.setWxuid(weiXinUserInfo.getUserid());
                        user.setName(weiXinUserInfo.getName());
                        user.setPhoto("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
                        userMapper.insert(user);
                    }
                    //维护组织和用户的关联关系
                    SysOrguser sysOrguser = sysOrguserMapper.selectByOrgUser(sysOrg.getId(), user.getId());
                    if(sysOrguser == null){
                        sysOrguser = new SysOrguser(sysOrg.getId(), user.getId());
                        sysOrguserMapper.insert(sysOrguser);
                    }
                }
            }catch (Exception e){
                logger.error("同步其他微信用户异常" + e.getMessage());
            }
        }
    }
}
